package org.chnxi.study.springcloud.dubbo.shiro.auth.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.chnxi.study.springcloud.dubbo.shiro.auth.entity.Permission;
import org.chnxi.study.springcloud.dubbo.shiro.auth.entity.Role;
import org.chnxi.study.springcloud.dubbo.shiro.auth.entity.User;
import org.chnxi.study.springcloud.dubbo.shiro.auth.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    //shiro的权限信息配置
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        String name = principalCollection.getPrimaryPrincipal().toString();

        User user = userService.findUserByName(name);

        List<Role> roles = userService.findRoles(user.getId());
        simpleAuthorizationInfo.setRoles(roles.stream().map(e->e.getRole()).collect(Collectors.toSet()));

        List<Permission> permissions = userService.findPermissions(user.getId());
        simpleAuthorizationInfo.setStringPermissions(permissions.stream().map(e->e.getName()).collect(Collectors.toSet()));
        return simpleAuthorizationInfo;
    }

    //根据token获取认证信息authenticationInfo
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String name = authenticationToken.getPrincipal().toString();
        User user = userService.findUserByName(name);

        if(null == user){
            return null;
        }
        ByteSource source = ByteSource.Util.bytes(user.getName());
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), source, getName());

        return simpleAuthenticationInfo;
    }

    //计算用户的密码
    public static void main(String[] args) {
        String hashAlgorithName = "md5";
        String password = "123456";
        int hashIterations = 1024;//加密次数
        ByteSource credentialsSalt = ByteSource.Util.bytes("zhangsan");
        Object obj = new SimpleHash(hashAlgorithName, password, credentialsSalt, hashIterations);
        System.out.println(obj);
    }
}
